//
//  TopicCommentViewController.swift
//  ReadHub
//
//  Created by testypp on 2018/1/2.
//  Copyright © 2018年 longyiqun. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import PKHUD
import SwiftMoment
import AvatarImageView
import SCLAlertView
import DZNEmptyDataSet


class TopicCommentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource,DZNEmptyDataSetDelegate {
	
	@IBOutlet weak var mainTable: UITableView!
	@IBOutlet weak var topicLabel: UILabel!
	@IBOutlet weak var sendCommentBtn: UIButton!
	
	
	// 全局变量
	var topic = Topic()
	var comments: NSMutableArray = []
	var interactor: Interactor? = nil

	let kInfoTitle = "写下你的小想法吧..."
	let kSubtitle = ""
	
	// 开始Load页面
	override func viewDidLoad() {
		
		super.viewDidLoad()
		
		// 获取topic title
		topicLabel.text = topic.title
		
		
		
		getComments()
	}
	
	func getComments() -> () {
		
		comments.removeAllObjects()
	
		// 准备URL
		let getCommentsURL: URLConvertible = Constants.getCommentsURL
		
		let para = ["topicid": String(self.topic.id!)]
		
		// FOR DEBUG
		//let para = ["topicid": "123"]
		
		// CALL API
		Alamofire.request(getCommentsURL, method: .get, parameters: para).responseJSON { response in
			
			if let JSONEntity = response.result.value {
				
				let jsonData = JSON(JSONEntity)
				
				// 判断是否登录成功
				if (jsonData["data"]["code"] == 0){
					
					// 循环取Topic填充数组
					for (_, topicDataArray): (String, JSON) in jsonData["data"]["info"] {
						
						// temp
						let comment = Comment()
						comment.commentstring = topicDataArray["commentstring"].string
						comment.id = topicDataArray["id"].string
						comment.ishot = topicDataArray["ishot"].string
						comment.topicid = topicDataArray["topicid"].string
						comment.time = topicDataArray["time"].string
						comment.userid = topicDataArray["userid"].string
						comment.username = topicDataArray["username"].string
						
						self.comments.add(comment)
					}
					
				}
			}
			
			self.setupUI()
		}
	}
	
	func setupUI() -> () {
		
		// 渲染评论列表
		//let mainTableRect: CGRect = CGRect(x: 0, y: Constants.statusBarHeight, width: self.view.bounds.width, height: self.view.bounds.height - Constants.statusBarHeight)
		//self.mainTableView = UITableView(frame: mainTableRect, style: UITableViewStyle.plain)
		self.mainTable.dataSource = self
		self.mainTable.delegate = self
		self.mainTable.register(UINib(nibName: "TopicCommentViewCell", bundle: nil), forCellReuseIdentifier: "TopicCommentViewCell")
		
		// 不显示侧边滑动条
		self.mainTable.showsVerticalScrollIndicator = false
		
		// Empty Table
		self.mainTable.separatorStyle = .none
		self.mainTable.emptyDataSetSource = self
		self.mainTable.emptyDataSetDelegate = self
		
		// 预估高度 （动态高度的时候一定要设置）
		self.mainTable.estimatedRowHeight = 100
		self.mainTable.rowHeight = UITableViewAutomaticDimension
		self.mainTable.reloadData()
	}
	
	// 返回条数
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		
		return comments.count
	}
	
	// 返回Section个数
	func numberOfSections(in tableView: UITableView) -> Int {
		return 1
	}
	
	// 返回主TableView的每一行
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		
		// cell重用
		if let cell = tableView.dequeueReusableCell(withIdentifier: "TopicCommentViewCell", for: indexPath) as? TopicCommentViewCell {
			
			// 当前行数
			let row: Int = indexPath.row
			
			// 点击cell样式
			cell.selectionStyle = .none
			
			// 获取评论用户nickname
			cell.nickNameLabel.text = (comments[row] as! Comment).username
			
			// 获取评论
			cell.commentStringLabel.text = (comments[row] as! Comment).commentstring
			
			// 取时间
			let timeMoment = moment() - moment((comments[row] as! Comment).time!, dateFormat: "yyy-MM-dd HH:mm:ss")!
			
			
			// 设置时间
			if (timeMoment.seconds < 60) {
				cell.timeLabel.text = "现在"
			} else if (timeMoment.minutes < 60) {
				cell.timeLabel.text = String(Int(timeMoment.minutes)) + " 分钟前"
			} else if (timeMoment.hours < 24) {
				cell.timeLabel.text = String(Int(timeMoment.hours)) + " 小时前"
			} else {
				cell.timeLabel.text = String(Int(timeMoment.days)) + " 天前"
			}
			
			// 设置评论用户头像
			struct Config: AvatarImageViewConfiguration { var shape: Shape = .square }
			cell.userImage.configuration = Config()
			
			
			let userImageDataSource = CommentUserImage(comments: comments, id: row)
			
			// 获取用户头像数据
			cell.userImage.dataSource = userImageDataSource
			
			return cell
		}
		
		return UITableViewCell()
		
	}
	
	// 结构体DataSource, 返回评论用户字母头像
	struct CommentUserImage: AvatarImageViewDataSource {
		var id: Int = 0
		var name: String = ""
		var avatar: UIImage?
		
		init(comments: NSMutableArray, id: Int) {
			
			let userName = (comments[id] as! Comment).username
			
			if( userName != nil) {
				name = userName!
			} else {
				name = ""
				avatar = UIImage(named: "login")
			}
		}
	}
	
	// 增加动画效果
	func animate(block: @escaping () -> Void, with delay: Double = 0.0) {
		DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay, execute: {
			UIView.animate(withDuration: 0.25, animations: {
				block()
			})
		})
	}
	
	// 增加手势监测
	@IBAction func handleGesture(_ sender: UIPanGestureRecognizer) {
		
		let percentThreshold:CGFloat = 0.3
		
		// 定义右划
		let translation = sender.translation(in: view)
		let fingerMovement = translation.x / view.bounds.width
		let rightMovement = fmaxf(Float(fingerMovement), 0.0)
		let rightMovementPercent = fminf(rightMovement, 1.0)
		let progress = CGFloat(rightMovementPercent)
		
		// 判断状态
		guard let interactor = interactor else { return }
		
		switch sender.state {
		case .began:
			interactor.hasStarted = true
			dismiss(animated: true, completion: nil)
		case .changed:
			interactor.shouldFinish = progress > percentThreshold
			interactor.update(progress)
		case .cancelled:
			interactor.hasStarted = false
			interactor.cancel()
		case .ended:
			interactor.hasStarted = false
			interactor.shouldFinish
				? interactor.finish()
				: interactor.cancel()
		default:
			break
		}
	}
	
	@IBAction func showCustomDialogTapped(_ sender: UIButton) {
		showCustomDialog()
	}
	
	func showCustomDialog(animated: Bool = true) {
		
		let customWidth = self.view.bounds.width * 0.8
		
		let appearance = SCLAlertView.SCLAppearance(kWindowWidth: customWidth, kTextViewdHeight: 100.0, showCloseButton: false, hideWhenBackgroundViewIsTapped: true)
		let alert = SCLAlertView(appearance: appearance)
		let textView = alert.addTextView()
		
		
		_ = alert.addButton("完成") {
			
			// 开始提交Comment
			if (textView.text != "") {
				// 准备URL
				let getCommentsURL: URLConvertible = Constants.submitCommentsURL
				
				let username = UserDefaults.standard.string(forKey: "username")
				let userid = UserDefaults.standard.string(forKey: "userid")
				
				var para = [String:String]()
				
				if (username != nil && userid != nil && username != "") {
				
					para = ["userid": userid!, "username": username!, "commentstring": textView.text!, "ishot": "1", "topicid": String(describing: self.topic.id!)]
					
				} else {
					
					para = ["userid": "00000", "username": "匿名", "commentstring": textView.text!, "ishot": "1", "topicid": String(describing: self.topic.id!)]
					
				}
				
				
				// CALL API
				Alamofire.request(getCommentsURL, method: .get, parameters: para).responseJSON { response in
					
					if let JSONEntity = response.result.value {
						
						let jsonData = JSON(JSONEntity)
						
						// 判断是否发表成功
						if (jsonData["data"]["code"] == 0){
							HUD.flash( HUDContentType.success, delay: 1)
							self.getComments()
						} else {
							HUD.flash( HUDContentType.error, delay: 1)
						}
					}
					
				}
			}
			
			print("Text value: \(textView.text ?? "NA")")
		}
		_ = alert.addButton("取消", backgroundColor: Constants.redColor) {
			print("Cancel")
		}
		
		_ = alert.showEdit(kInfoTitle, subTitle:"", colorStyle: 0x2B3347)
	}
	
	//实现第三方库协议的方法
	func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
		let text = "暂无评论, 发一个吧!"
		let attributes = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: CGFloat(16.0)), NSAttributedStringKey.foregroundColor: UIColor.darkGray]
		return NSAttributedString(string: text, attributes: attributes)
	}
	
	// Empty Table的IMAGE
	func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
		return UIImage(named: "no_comment")
	}
	
	func backgroundColor(forEmptyDataSet scrollView: UIScrollView!) -> UIColor! {
		return UIColor.white
	}
	
	func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
		return true
	}
	func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView!) -> Bool {
		return true
	}
	func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
		return false
	}
	func emptyDataSetShouldAnimateImageView(_ scrollView: UIScrollView!) -> Bool {
		return false
	}
	
}
